package com.httpClient.chapter1;

import com.sky.JULLog.MyJulLogger;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * @author : wushikai
 * date : 2024-06-17
 */
public class InterceptorHttpClient {


    private static Logger log = MyJulLogger.getLogger(InterceptorHttpClient.class);


    /**
     * 没有理解应用场景, {@link HttpContext } 这个类也不知道是干吗用的
     */
    private static HttpRequestInterceptor httpRequestInterceptor = new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context) {

            AtomicInteger count = (AtomicInteger) context.getAttribute("count");
            request.addHeader("Count", Integer.toString(count.getAndIncrement()));

        }
    };

    public static void main(String[] args) throws Exception {
        doRequest();
    }


    private static void doRequest() throws IOException {


        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        AtomicInteger count = new AtomicInteger(1);
        localContext.setAttribute("count", count);

        httpclient.addRequestInterceptor(httpRequestInterceptor);
        HttpGet httpget = new HttpGet("http://localhost:8080/xy/expose/merDetail");
        for (int i = 0; i < 10; i++) {
            HttpResponse response = httpclient.execute(httpget, localContext);
            handleResponse(response);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
        }


    }


    /**
     * 使用最简单的 流式读取
     */
    private static void handleResponse(HttpResponse response) throws IOException {

        log.info("response 的实现类是==>" + response.getClass().getCanonicalName());
        log.info("协议版本:" + response.getProtocolVersion());
        log.info("服务器返回状态码:" + response.getStatusLine().getStatusCode());
        log.info("服务器返回状态码表述:" + response.getStatusLine().getReasonPhrase());
        log.info("服务器返回状态描述:" + response.getStatusLine().toString());

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.warning("响应结果不是200, 直接返回");
            return;
        }


        //使用 响应头 获取 cookie 键值对,  注意这是没有被解析过的
        Header h1 = response.getFirstHeader("Set-Cookie");
        log.info("" + h1);  //mark 不知道为什么这是空的


        //使用 迭代器 获取 cookie 键值对 ,  httpClient 帮你解析好;
        HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));
        while (it.hasNext()) {
            HeaderElement elem = it.nextElement();
            log.info(elem.getName() + " = " + elem.getValue());
            NameValuePair[] params = elem.getParameters();
            for (NameValuePair param : params) {
                log.info(" " + param);
            }
        }


        HttpEntity entity = response.getEntity();   // 返回一个 HttpResponse 的 entity(实体) 这个  实体 = 响应头+响应内容

        if (entity != null) {
            InputStream inputStream = entity.getContent();   //实体对象 获取流 , 解析data 即可;
            byte[] buffer = new byte[2048];
            while (inputStream.read(buffer) != -1) {
                log.info("第一次读取的内容是:" + new String(buffer, StandardCharsets.UTF_8));
            }
            System.out.println();
            System.out.println("data  read  finished.......");
            inputStream.close();

        }


    }

}


